import React, { useState } from "react";
interface AvatarProps {
  src?: string | null;
  alt?: string;
  size?: "sm" | "md" | "lg";
  onClick?: () => void;
}

/**
 * 用户头像组件
 *
 * 显示用户头像，如果没有提供src，则显示默认头像
 * @author BelovedLYC
 */
const Avatar: React.FC<AvatarProps> = ({
  src,
  alt = "用户头像",
  size = "md",
  onClick,
}) => {
  // 默认头像
  // 声明状态存储加载后的资源
  const [defaultAvatar, setDefaultAvatar] = useState<string>(
    "https://beloved-1308416229.cos.ap-chengdu.myqcloud.com/images/avatar.jpg"
  );

  // 根据尺寸设置类名
  const sizeClasses = {
    sm: "h-8 w-8",
    md: "h-10 w-10",
    lg: "h-12 w-12",
  };

  return (
    <div
      className={`relative rounded-full overflow-hidden flex-shrink-0 ${sizeClasses[size]} bg-gray-100 dark:bg-gray-700 cursor-pointer hover:ring-2 hover:ring-blue-500 transition-all duration-200`}
      onClick={onClick}
    >
      <img
        src={src || defaultAvatar}
        alt={alt}
        className="h-full w-full object-cover"
        onError={(e) => {
          // 图片加载失败时使用默认头像
          (e.target as HTMLImageElement).src = defaultAvatar;
        }}
      />
    </div>
  );
};

export default Avatar;
